package cn.frank.framework.caesar.module.ai.qwen.rest;

import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.community.model.dashscope.QwenStreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.extensions.Extension;
import io.swagger.v3.oas.annotations.extensions.ExtensionProperty;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @description: TODO
 * @author: renjiangyang
 * @date 2025/6/7 14:43:51
 * @since 1.8
 */
@Tag(name = "1 会话-基本", description = "QwenChat", extensions = {
        @Extension(properties = {@ExtensionProperty(name = "x-order", value = "1", parseValue = true)}
        )
})
@RestController
@RequestMapping("/ai/qwen")
public class QwenChatRestController extends BaseQwenRestController {

    @Autowired
    QwenChatModel chatModel;

    @Autowired
    QwenStreamingChatModel streamingChatModel;

    @Operation(summary = "提问")
    @GetMapping("/chat")
    public String test(@RequestParam(defaultValue = "你是谁") String message) {
        String chat = chatModel.chat(message);
        return chat;
    }

    @Operation(summary = "提问（Stream）")
    @GetMapping(value = "/stream", produces = "text/stream;charset=UTF-8")
    public Flux<String> stream(@RequestParam(defaultValue = "你是谁") String message) {
        Flux<String> flux = Flux.create(fluxSink -> {
            streamingChatModel.chat(message, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String partialResponse) {
                    System.out.println("completeResponse = " + partialResponse);
                    fluxSink.next(partialResponse);
                }

                @Override
                public void onCompleteResponse(ChatResponse completeResponse) {
                    System.out.println("over");
                    fluxSink.complete();
                }

                @Override
                public void onError(Throwable error) {
                    fluxSink.error(error);
                }
            });
        });
        return flux;
    }
}
